﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonAsyncDemoFunctions
{
	public static class ErrorExtension
	{
		public static Task<T> HandleErrors<T>(this Task<T> task)
		{
			return task.ContinueWith<T>((t) =>
				{
					if (t.Exception != null)
					{
						foreach (var e in t.Exception.Flatten().InnerExceptions)
						{
							if (e is Exception)
							{
								//Do your comomon exception handling here 
								Console.WriteLine("ARRRGGGGH " + e.Message);
							}
						}
						return default(T);
					}
					else
					{
						return t.Result;
					}
				});
		}

		public static Task<T> HandleErrors<T>(this Task<T> task, Action<Exception> exceptionHandler)
		{
			return task.ContinueWith<T>((t) =>
			{
				if (t.Exception != null)
				{
					t.Exception.Flatten().InnerExceptions.ToList().ForEach(ex => exceptionHandler(ex));
					return default(T);
				}
				else
				{
					return t.Result;
				}
			});
		}

		public static Task HandleErrors(this Task task)
		{
			return task.ContinueWith((t) =>
			{
				if (t.Exception != null)
				{
					foreach (var e in t.Exception.Flatten().InnerExceptions)
					{
						if (e is Exception)
						{
							//Do your comomon exception handling here
							Console.WriteLine("ARRRGGGGH " + e.Message);
						}
					}
				}
			});
		}

		public static Task HandleErrors(this Task task, Action<Exception> exceptionHandler)
		{
			return task.ContinueWith((t) =>
			{
				if (t.Exception != null)
				{
					t.Exception.Flatten().InnerExceptions.ToList().ForEach(ex => exceptionHandler(ex));
				}
			});
		}
	}
}
